package com.sf.iguess.survey.controller;

import java.io.File;
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.sf.iguess.response.JsonResult;
import com.sf.iguess.response.ResponseCode;
import com.sf.iguess.survey.constant.Constant;
import com.sf.iguess.survey.domain.Answer;
import com.sf.iguess.survey.domain.User;
import com.sf.iguess.survey.domain.UserScore;
import com.sf.iguess.survey.service.AnswerService;
import com.sf.iguess.survey.service.UserScoreService;

/**
 * @author 80002286
 * @date 2017年12月4日
 * @time 下午8:53:31
 * @description 
 */
@RequestMapping("answer")
@Controller
public class AnswerController {
	
	@Resource
	private AnswerService answerService;
	
	@Resource
	private UserScoreService userScoreService;
	
	@PostMapping("/save")
	@ResponseBody
	public JsonResult save(String answerJson, UserScore userScore,
			@RequestParam(value = "files", required = false) MultipartFile[] files,
			HttpSession session){
		User userInfo = (User) session.getAttribute(Constant.USER_INFO);
		if(null == userInfo){
			return null;
		}
//		validate();
		List<Answer> answerList = JSON.parseArray(answerJson,Answer.class);
		for (MultipartFile file : files) {
			try {
				String[] fileName = file.getOriginalFilename().split("\\.");
				Integer index = Integer.parseInt(fileName[0])-1;
				File targetFile = fileHandle(file);
				
				answerList.get(index).setFileLink(targetFile.getPath());
			} catch (NumberFormatException e) {
				e.printStackTrace();
			} catch (IllegalStateException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		int count = countPoint(answerList);
		
		userScore.setScore(count);
		userScore.setStatus(count > 59?1:0);
		answerService.saveAnswer(answerList, userScore);
		
		return new JsonResult(ResponseCode.SUCCESS,"",null);
	}
	
	

	/**
	 * 计算得分
	 * @param answerList
	 * @return
	 */
	private int countPoint(List<Answer> answerList) {
		int count = 1;
		for (Answer answer : answerList) {
			count += answer.getChoseValue();
			Integer serialNumber = answer.getSerialNumber();
			if("1".equals(serialNumber.toString())){
				Integer point = answer.getChoseValue();
				String reply = answer.getReply();
				if(point == 3 || reply.contains("等级保护")){
					count += 5;
				}
			}
		}
		return count;
	}
	
	@RequestMapping("/findAnswerInfo")
	@ResponseBody
	public JsonResult findAnswerInfo(String scoreId){
		List<Answer> answerList = answerService.findByScoreId(scoreId);
		return new JsonResult(ResponseCode.SUCCESS,"",answerList);
	}
	
	/**
	 * 校验是否填写了必填项目
	 * @return
	 */
	public boolean validate(){
		
		return false;
	}
	
	/**
	 * 处理文件信息，并创建相应文件夹
	 * @param file
	 * @param menuId		指定路径下，以menuId
	 * @param path			linux/window的指定路径
	 * @param folderName	以固定文件名命名，null则用年月命名
	 * 
	 * @return
	 * @throws IOException 
	 * @throws IllegalStateException 
	 */
	private File fileHandle(MultipartFile file) throws IllegalStateException, IOException {
		long curTime = System.currentTimeMillis();
		String fileName = file.getOriginalFilename();
		String[] fileNameArr = fileName.split(Constant.SUFFIXRULE);
		String randomNum = randomNum();
		
		String path = Constant.getOsPath();
		
		String ruleFileName = fileNameArr[0] + curTime + randomNum;
		String md5Name = DigestUtils.md5DigestAsHex(ruleFileName.getBytes());
		fileName = md5Name + "." + fileNameArr[1];
		path = getPath(path);
		if(null == path){
			return null;
		}
		
		File targetFile = new File(path, fileName);
		if(!targetFile.exists()){
		    targetFile.mkdirs();
		}
		
		file.transferTo(targetFile);
		return targetFile;
	}
	
	/**
	 * 获取当日文件夹路径
	 * @param home
	 * @param path
	 * @return
	 */
	private String getPath(String path) {
		Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH)+1;
        int date = calendar.get(Calendar.DATE);
        
		path += year+"-"+month+"-"+date;
        
		return path;
	}

	/**
	 * 生成4位数随机数
	 * @return
	 */
	public String randomNum(){
		Random random = new Random();
		String randomNum = "";
		for (int i = 0; i < 4; i++) {
			randomNum += String.valueOf(random.nextInt(9));
		}
		return randomNum;
	}
	
	public String randomUUID(){
		return UUID.randomUUID().toString();
	}
	
}
